package com.anhndt.audiobook.ui;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.utils.DBUtil;
import com.anhndt.audiobook.utils.DialogUtil;
import com.anhndt.audiobook.utils.StringUtil;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.layouts.BorderLayout;

import com.sun.lwuit.list.DefaultListCellRenderer;
import com.sun.lwuit.plaf.DefaultLookAndFeel;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Hashtable;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.midlet.*;
import javax.wireless.messaging.MessageConnection;

//#if BB || BB_Touch|| BB_BOLD
//# import net.rim.device.api.system.Characters;
//# import net.rim.device.api.ui.Keypad;
//# import com.sun.lwuit.events.ActionEvent;
//# import com.sun.lwuit.events.ActionListener;
//# import com.sun.lwuit.impl.blackberry.BlackBerryImplementation;
//# import com.sun.lwuit.TextField;
//# import com.anhndt.audiobook.business.MediaPlayerControl;
//# import com.sun.lwuit.plaf.DefaultLookAndFeel;
//#endif
/**
 * @author Sun
 */
public class AudioStore extends MIDlet {

    private static final int PORT_MESSAGE = 2222;
    private static MessageConnection mesageConnection;
    private static Resources resource;
    private static MIDlet instance = null;
//    static int sizeRes = 56;

//    public static int getSizeRes() {
//        return sizeRes;
//    }

    static void detectAllConfig() {
//        int density = Util.getDeviceDensity();
//        if (density < Util.DENSITY_LOW) {
//            Util.sizeThumbHit = 56;
//        } else if (density < Util.DENSITY_MEDIUM) {
//            Util.sizeThumbHit = 75;
//        } else {
//            Util.sizeThumbHit = 121;
//        }
////#if BB_BOLD || BB_Touch || J2ME_78
//        sizeRes = 78;
//        APP_PACKAGE_ID = 5;
////#elif J2ME_40
////#         sizeRes = 46;
//        //#         Util.sizeThumb = 40;
////#         APP_PACKAGE_ID = 1;
////#elif J2ME_64
////#         sizeRes = 64;
////#         APP_PACKAGE_ID = 3;
////#endif

        //Util.sizeThumb = 56;
        int size = 56;
//#if BB
//#         size = 56;
//#elif BB_BOLD
//#         size = 78;
//#elif BB_Touch
//#         size = 78;
//#elif J2ME_32
//#         size = 32;
//#elif J2ME_40
//#         size = 40;
//#elif J2ME_56
//#         size = 56;
//#elif J2ME_64
//#         size = 64;
//#elif Dev
//#         size = 56;
//#         APP_PACKAGE_ID = 2;
//#endif
        Util.sizeThumb = size;
        if(size <= 56) {
            Util.sizeThumbHit = Util.sizeThumb;
        } else {
            Util.sizeThumbHit = Util.sizeThumb * 3 / 2;
        }
        
    }

    public void loadConfig() {
        DBUtil.deleteRecordStore(DBUtil.DB_IMAGE);
        DBUtil.loadSetting();
    }

    public static String getPathResource() {
        return "/themes/blue/" + Util.sizeThumb + "/audiostore.b";
    }

    private void start() throws IOException {
        instance = this;
        Display.init(this);
        Display.getInstance().flashBacklight(10 * 60 * 1000);
        Dialog.setCommandsAsButtons(false);
        //load all config in RMS 
        loadConfig();
        detectAllConfig();
        try {
            String themeID = DBUtil.getValue(DBUtil.DB_RECORD_THEME_ID, "0");
            if (!themeID.equals("0")) {
                ByteArrayInputStream bis = new ByteArrayInputStream(DBUtil.loadData(DBUtil.DB_THEME, themeID));
                resource = Resources.open(bis);
            } else {
                resource = Resources.open(getPathResource());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                resource = Resources.open(getPathResource());
            } catch (IOException ex1) {
                ex1.printStackTrace();
            }
        }
//#if BB_Lite || Lite
//#         com.sun.lwuit.Label.setDefaultTickerEnabled(false);
//#else
//        UIManager.getInstance().setLookAndFeel(new CustomLookAndFeel());
//#endif
        UIManager.getInstance().setThemeProps(resource.getTheme(resource.getThemeResourceNames()[0]));
        Label.setDefaultTickerEnabled(getValueL10N("ticker").equals("1"));
        boolean checkTouchDevice = getValueL10N("check_touch_device").equals("1");
        boolean checkTouchMenu = getValueL10N("touch_menu").equals("1");

        boolean touchMenu = checkTouchMenu;
        if (checkTouchDevice) {
            touchMenu = Display.getInstance().isTouchScreenDevice();
        }
        if (touchMenu) {
            UIManager.getInstance().getLookAndFeel().setTouchMenus(touchMenu);
        }
        DefaultLookAndFeel lookAndFeel = (DefaultLookAndFeel) UIManager.getInstance().getLookAndFeel();
        DefaultListCellRenderer menuRenderer = new DefaultListCellRenderer() {

            public Component getListFocusComponent(List list) {
                return null;
            }
        };
        menuRenderer.setUIID("MenuRenderer");
        lookAndFeel.setMenuRenderer(menuRenderer);
        lookAndFeel.setCheckBoxImages(Util.getImage("checked"), Util.getImage("uncheck"));

        if (!Display.getInstance().isTouchScreenDevice()) {
            lookAndFeel.setDefaultSmoothScrolling(false);
        }

        lookAndFeel.setReverseSoftButtons(true);
        // Disable scrolling
        Dialog.setDisableStaticDialogScrolling(true);
        Dialog.setDefaultDialogPosition(BorderLayout.CENTER);
        //add volume listener
//#if BB || BB_Touch|| BB_BOLD
//#         if (Keypad.getHardwareLayout() == Keypad.HW_LAYOUT_32) {
//#             TextField.setReplaceMenuDefault(false);
//#         }
//#         BlackBerryImplementation.addVolumeListener(new ActionListener() {
//# 
//#             public void actionPerformed(ActionEvent evt) {
//#                 char c = (char) evt.getKeyEvent();
//#                 if (c == Characters.CONTROL_VOLUME_UP) {
//#                     MediaPlayerControl.incrementVolume();
//#                 } else if (c == Characters.CONTROL_VOLUME_DOWN) {
//#                     MediaPlayerControl.decrementVolume();
//#                 }
//#             }
//#         });
//#endif
//        new TestMediaPlayerForm();
        new LoginForm(null).show();
    }

    public void startApp() {
        if (instance != null) {
            return;
        }
        instance = this;
        try {
            start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public static void applyTheme(Resources resource) {
        AudioStore.resource = resource;
        UIManager.getInstance().setThemeProps(resource.getTheme(resource.getThemeResourceNames()[0]));
        Display.getInstance().getCurrent().refreshTheme();
        DialogUtil.showInfoDialog(Resource.TXT_CHANGED, true);
        Util.gc();
    }

    public static MIDlet getInstance() {
        return instance;
    }

    public static Resources getResource() {
        return resource;
    }

    public static void setResource(Resources resource) {
        AudioStore.resource = resource;
    }

    public static void exitApp() {
        exitApp(true);
    }

    public static void exitApp(boolean confirm) {
        if (!confirm) {
            instance.notifyDestroyed();
            return;
        }
        String msg = StringUtil.format(Resource.TXT_CONFIRM_EXIT_APP, new String[]{"" + Util.getData()});
        Command c = DialogUtil.showConfirmDialog(msg, new String[]{Resource.CMD_OK, Resource.CMD_CANCEL});
        if (c != null && c.getCommandName().equalsIgnoreCase(Resource.CMD_OK)) {
            if (!StringUtil.isNullOrEmpty(Util.lastArticleID)) {
                DBUtil.changeValue(DBUtil.DB_RECORD_LAST_ARTICLE_ID, "" + Util.lastArticleID);
            }
            DBUtil.deleteRecordStore(DBUtil.DB_IMAGE);
            instance.notifyDestroyed();
        }
    }

    public static void execute(String url) {
        System.out.println("execute : " + url);
        try {
            instance.platformRequest(url);
        } catch (ConnectionNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    public static String getValueL10N(String key) {
        try {
            Hashtable l10n = resource.getL10N("CONFIG", "en");
            return l10n.get(key).toString();
        } catch (Exception e) {
            return "";
        }
    }
}
